package com.shiwenping.reply;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.andreabaccega.widget.FormEditText;
import com.jakewharton.rxbinding2.view.RxView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.shiwenping.reply.data.Repository;
//import com.shiwenping.reply.databinding.ActivityLoginBinding;
import com.shiwenping.reply.databinding.ActivityLoginBinding;
import com.shiwenping.reply.net.ApiManager;
import com.shiwenping.reply.net.RxDownLoadManager;
import com.shiwenping.reply.net.body.LoginBeen;
import com.shiwenping.reply.net.domain.FaqImageListBean;
import com.shiwenping.reply.net.domain.FaqItemResult;
import com.shiwenping.reply.net.domain.FileItemResult;
import com.shiwenping.reply.net.service.AllService;
import com.shiwenping.reply.tools.Path;
import com.shiwenping.reply.tools.sp.SharedPreferenceUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.realm.RealmObject;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * 登录界面
 *
 * @author shiwenping
 */
@Route(path = Path.MAIN_LOGIN)
public class LoginActivity extends BaseActivity<ActivityLoginBinding> {
    /**
     * 进度条
     */
    private KProgressHUD kProgressHUD;

    private Repository repository;

    private RxPermissions rxPermissions;

    private final String[] pre = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (!TextUtils.isEmpty(SharedPreferenceUtil.get(this, Path.TOKEN, ""))) {
            ARouter.getInstance().build(Path.MAIN_PATH).navigation(this, new NavCallback() {
                @Override
                public void onArrival(Postcard postcard) {
                    finish();
                }
            });
        }
        super.onCreate(savedInstanceState);
        rxPermissions = new RxPermissions(this);
        repository = Repository.getRepository(this);
        kProgressHUD = KProgressHUD.create(this);

        RxView.clicks(databinding.loginBtn)
                .compose(rxPermissions.ensure(pre))
                .subscribe(o -> login());
    }


    /**
     * 点击事件
     */
    private void login() {
        String userName = ((FormEditText) findViewById(R.id.userName)).getText().toString().trim();
        String userPass = ((FormEditText) findViewById(R.id.userPass)).getText().toString().trim();
        boolean userNameValid = ((FormEditText) findViewById(R.id.userName)).testValidity();
        boolean userPassValid = ((FormEditText) findViewById(R.id.userPass)).testValidity();

        if (userNameValid && userPassValid) {
            ApiManager.retrofit(this)
                    .create(AllService.class)
                    .loginUserName(new LoginBeen(userName, userPass, "").build())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .flatMap(loginResult -> {
                        if (loginResult.isSuccess()) {
                            SharedPreferenceUtil.put(getActivity(), Path.TOKEN, loginResult.getAuth());
                            kProgressHUD.setLabel("登录成功，开始下载");
                            return Observable.merge(repository.getFaqList(false),repository.getFileList(false));
                        } else {
                            kProgressHUD.setLabel("登录失败").dismiss();
                            return Observable.error(new Throwable("登录失败"));
                        }
                    })
                    .flatMap(results -> {
                        List<Observable<String>> observables = new ArrayList<>();
//                        Log.d("HaiChecker","返回的数据大小:"+results.size());
//                        Log.d("HaiChecker","类型:"+results.getClass().getProtectionDomain());
                        if (results != null && results.size() > 0)
                        {
                            Log.d("HaiChecker","是否为知识库:"+(results.get(0) instanceof FaqItemResult)+"类型:"+results.get(0).getClass().getName());
                            if (results.get(0) instanceof FaqItemResult)
                            {
                                for (RealmObject temp : results) {
                                    FaqItemResult result = (FaqItemResult) temp;
                                    if (!TextUtils.isEmpty(result.getFaq_image_url())) {
                                        observables.add(RxDownLoadManager.download( result.getFaq_image_url()));
                                    }
                                    if (result.getFaq_image_list() != null) {
                                        for (FaqImageListBean faqImageListBean : result.getFaq_image_list()) {
                                            observables.add(RxDownLoadManager.download( faqImageListBean.getUrl()));
                                        }
                                    }
                                }
                            }else {
                                for (RealmObject temp : results) {
                                    FileItemResult result = (FileItemResult) temp;
                                    if (!TextUtils.isEmpty(result.getFile_http_url())){
                                        observables.add(RxDownLoadManager.download(result.getFile_http_url()));
                                    }
                                }
                            }
                        }
                        return Observable.merge(observables);
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(() -> kProgressHUD.setLabel("登录中").show())
                    .subscribe(results -> {
                        Log.d("HaiChecker", "下载了一个:"+results);
                    }, throwable -> {
                        kProgressHUD.setLabel(throwable.getMessage()).dismiss();
                        throwable.printStackTrace();
                    }, () -> {
                        kProgressHUD.setLabel("下载成功！").dismiss();
                        ARouter.getInstance().build(Path.MAIN_PATH).navigation();
                        finish();
                    });

        }
    }

    @Override
    int resLayout() {
        return R.layout.activity_login;
    }
}
